<template>
    <div class="app-container">

        <div class="filter-container">

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="课程ID" v-model="listQuery.searchCourseId" @keypress='validateNumber($event)'>
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="课程名称" v-model="listQuery.searchName">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="订单ID" v-model="listQuery.searchOrderSn" @keypress='validateNumber($event)'>
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="手机号码" v-model="listQuery.searchPhone" @keypress='validateNumber($event)'>
            </el-input>

        </div>

        <div class="filter-container">

                <el-date-picker
                        v-model="listQuery.searchCreateTimeStart"
                        type="date"
                        placeholder="创建订单开始日期"
                        format="yyyy-MM-dd"
                        :picker-options="pickerStartOption">
                </el-date-picker>

                <el-date-picker
                        v-model="listQuery.searchCreateTimeEnd"
                        type="date"
                        placeholder="创建订单结束日期"
                        :picker-options="pickerEndOption">
                </el-date-picker>

                <el-date-picker
                        v-model="listQuery.searchPayTimeStart"
                        type="date"
                        placeholder="支付完成开始日期"
                        format="yyyy-MM-dd"
                        :picker-options="pickerStartOption">
                </el-date-picker>

                <el-date-picker
                        v-model="listQuery.searchPayTimeEnd"
                        type="date"
                        placeholder="支付完成结束日期"
                        :picker-options="pickerEndOption">
                </el-date-picker>

        </div>

        <div class="filter-container">

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.searchStatus" placeholder="选择订单状态" @change="handleFilter">
                <el-option v-for="item in statusOptions" :key="item" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.searchResource" placeholder="选择订单来源" @change="handleFilter">
                <el-option v-for="item in resourceOptions" :key="item" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.orderKey" placeholder="排序" @change="handleFilter">
                <el-option v-for="item in orderKeyOptions" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
            </el-select>

            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" type="warning" icon="delete2" @click="resetQuery">重置</el-button>
            <el-button class='filter-item' type="primary" icon="document" @click="handleDownload">导出excel</el-button>

        </div>

        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row :row-class-name="tableRowClassName">

            <el-table-column label='自增ID' align="center" width="80">
                <template scope="scope">
                    {{scope.row.id}}
                </template>
            </el-table-column>

            <el-table-column label='订单ID' align="center" width="240">
                <template scope="scope">
                    {{scope.row.orderSn}}
                </template>
            </el-table-column>
            <el-table-column label="课程名称" align="center" width="200">
                <template scope="scope">
                    {{scope.row.courseName}}
                </template>
            </el-table-column>
            <el-table-column label="应付金额" align="center" width="100">
                <template scope="scope">
                    ￥{{scope.row.discPrice|priceFormat}}
                </template>
            </el-table-column>
            <el-table-column label="实付金额" align="center" width="100">
                <template scope="scope">
                    ￥{{scope.row.discPrice|priceFormat}}
                </template>
            </el-table-column>
            <el-table-column label="手机号码" align="center" width="120">
                <template scope="scope">
                    {{scope.row.phone}}
                </template>
            </el-table-column>
            <el-table-column label="订单状态" align="center" width="100">
                <template scope="scope">
                    {{scope.row.status|parseOrderStatus}}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="180">
                <template scope="scope">
                    <span>{{scope.row.createTime|parseTime}}</span>
                </template>
            </el-table-column>
            <el-table-column label="支付时间" align="center" width="180">
                <template scope="scope">
                    <span>{{scope.row.payTime|parseTime}}</span>
                </template>
            </el-table-column>
            <el-table-column label="支付方式" align="center" width="120">
                <template scope="scope">
                    <span>{{scope.row.payType|parsePayType}}</span>
                </template>
            </el-table-column>
            <el-table-column label="订单来源" align="center" width="120">
                <template scope="scope">
                    <span>{{scope.row.channel|parseChannel}}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" min-width="250" fixed="right">
                <template scope="scope">

                    <el-button class="filter-item" size="small" type="primary" icon="edit" @click="handleEdit(scope.row.orderSn)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import { getList } from '@/api/statorder';
    import { priceFormat, parseTime, parsePayType, parseChannel, parseOrderStatus } from '@/filters/index';
    import { getOrderKey } from '@/api/common';

    var defaultListQuery = {
        page: 1,
        pageSize: 30,
        searchId: '',
        searchOrderSn: '',
        searchName: '',
        searchStatus: '',
        searchPhone: '',
        searchCourseId: '',
        searchResource: '',
        searchCreateTimeStart: '',
        searchCreateTimeEnd: '',
        searchPayTimeStart: '',
        searchPayTimeEnd: '',
        orderKey: 'CREATE_TIME_DESC'
    }

    export default {
        data() {
            var listQuery = JSON.parse(JSON.stringify(defaultListQuery));
            var listQueryJson = sessionStorage.getItem(this.$route.path.replace(/\//g, '_'));
            if (listQueryJson) {
                listQuery = JSON.parse(listQueryJson);
            }
            return {
                list: null,
                total: null,
                resourceOptions: [
                    { name: '选择渠道', key: '' },
                    { name: '泰迪熊', key: 'TED' },
                    { name: '微信', key: 'WX' },
                    { name: '其他', key: 'OTHER' }
                ],
                orderKeyOptions: [
                ],
                statusOptions: [
                    { name: '待支付', key: '0' },
                    { name: '支付成功', key: '1' },
                    { name: '支付失败', key: '2' },
                    { name: '用户取消', key: '3' },
                    { name: '超时取消', key: '4' }
                ],
                listQuery: listQuery,
                listLoading: true,
                pickerStartOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                pickerEndOption: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                selectedRowID: sessionStorage.getItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
            }
        },
        created() {
            this.getList();
            this.getOrderKeyList();
        },
        methods: {
            resetQuery() {
                this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
                this.selectedRowID = '';
                sessionStorage.removeItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
                this.getList();
            },
            tableRowClassName(row) {
                if (this.selectedRowID && row.id == this.selectedRowID) {
                    return 'sstt-selected-row';
                }
            },
            getList() {
                if (this.checkParamError()) {
                    this.$message({
                        title: '参数错误',
                        message: this.checkParamError(),
                        type: 'error',
                        duration: 1000
                    });
                    return;
                }
                this.listLoading = true;
                if (typeof this.listQuery.searchCreateTimeStart == 'object') {
                    this.listQuery.searchCreateTimeStart = parseTime(this.listQuery.searchCreateTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchCreateTimeEnd == 'object') {
                    this.listQuery.searchCreateTimeEnd = parseTime(this.listQuery.searchCreateTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                if (typeof this.listQuery.searchPayTimeStart == 'object') {
                    this.listQuery.searchPayTimeStart = parseTime(this.listQuery.searchPayTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof this.listQuery.searchPayTimeEnd == 'object') {
                    this.listQuery.searchPayTimeEnd = parseTime(this.listQuery.searchPayTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                getList(this.listQuery).then(response => {
                    this.list = response.data.data;
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                    sessionStorage.setItem(this.$route.path.replace(/\//g, '_'), JSON.stringify(this.listQuery));
                }).catch(err => {
                    console.log(err)
                    this.listLoading = false;
                });
            },
            getOrderKeyList() {
                getOrderKey('base').then(response => {
                    this.orderKeyOptions = this.orderKeyOptions.concat(response.data);
                }).catch(err => {
                    console.log(err)
                });
            },
            handleFilter() {
                this.getList();
            },
            handleEdit(id) {
                sessionStorage.setItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id', id)
                this.$router.push('/statorder/detail/' + id);
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleDownload() {
                if (this.checkParamError()) {
                    this.$message({
                        title: '参数错误',
                        message: this.checkParamError(),
                        type: 'error',
                        duration: 1000
                    });
                    return;
                }
                const copyQuery = JSON.parse(JSON.stringify(this.listQuery));
                copyQuery.page = 1;
                copyQuery.pageSize = 1000;
                if (typeof copyQuery.searchCreateTimeStart == 'object') {
                    copyQuery.searchCreateTimeStart = parseTime(copyQuery.searchCreateTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof copyQuery.searchCreateTimeEnd == 'object') {
                    copyQuery.searchCreateTimeEnd = parseTime(copyQuery.searchCreateTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                if (typeof copyQuery.searchPayTimeStart == 'object') {
                    copyQuery.searchPayTimeStart = parseTime(copyQuery.searchPayTimeStart, '{y}-{m}-{d} 00:00:00');
                }
                if (typeof copyQuery.searchPayTimeEnd == 'object') {
                    copyQuery.searchPayTimeEnd = parseTime(copyQuery.searchPayTimeEnd, '{y}-{m}-{d} 23:59:59');
                }
                getList(copyQuery).then(response => {
                    const dataList = response.data.data;
                    require.ensure([], () => {
                        const { export_json_to_excel } = require('@/vendor/Export2Excel');
                        dataList.forEach(item => {
                            item.discPrice = priceFormat(item.discPrice);
                            item.createTime = parseTime(item.createTime);
                            item.status = parseOrderStatus(item.status);
                            item.payTime = parseTime(item.payTime);
                            item.payType = parsePayType(item.payType);
                            item.channel = parseChannel(item.channel);
                        });
                        const tHeader = ['订单号', '课程名称', '应付金额', '实付金额', '手机号码',
                            '订单状态', '创建时间', '支付时间', '支付方式', '支付交易ID', '订单来源'];
                        const filterVal = ['orderSn', 'courseName', 'discPrice', 'discPrice', 'phone',
                            'status', 'createTime', 'payTime', 'payType', 'payTradeId', 'channel'];
                        const data = this.formatJson(filterVal, dataList);
                        export_json_to_excel(tHeader, data, '订单统计');
                    })
                }).catch(err => {
                    console.log(err)
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
            validateNumber(event) {
                var isNumber = event.charCode >= 48 && event.charCode <= 57
                var res = isNumber && this.phone.length < 32;
                if (!res) {
                    event.preventDefault();
                }
                return res;
            },
            checkParamError() {
                if (this.listQuery.searchCourseId && !/^\d*$/.test(this.listQuery.searchCourseId)) {
                    return '课程ID必须是数字';
                }
                if (this.listQuery.searchOrderSn && !/^\d*$/.test(this.listQuery.searchOrderSn)) {
                    return '订单ID必须是数字';
                }
                if (this.listQuery.searchPhone && !/^\d{11}$/.test(this.listQuery.searchPhone)) {
                    return '手机号必须是11位数字';
                }
                return '';
            }
        }
    };
</script>